<!-- form表单组件 -->
<template>
	<form class="validate-form-container">
		<slot></slot>
		<!-- click.prevent 阻止事件的默认行为 -->
		<div class="submit-area" @click.prevent="submitForm">
			<!-- 具名插槽 -->
			<slot name="submit">
				<!-- 默认按钮 -->
				<button type="submit" class="btn btn-primary">提交</button>
			</slot>
		</div>
	</form>
</template>

<script lang="ts">
import { defineComponent, onUnmounted } from "vue";
import mitt from "mitt"; // 引入mitt 代替bus事件总线
type ValidateFunc = () => boolean; // 函数类型形状  是个函数
export const emitter = mitt();
export default defineComponent({
	name: "ValidateForm",
	emits: ["form-submit"],
	setup(props, context) {
		let funcArr: ValidateFunc[] = []; // 数组中的每一项都是一个函数
		const submitForm = () => {
			const result = funcArr
				.map((func) => func()) // 执行数组中的每一项函数  得到返回值true或false
				.every((result) => result); // 全部是true才返回true 否则返回false

			context.emit("form-submit", result);
		};
		const callback = (func: any) => {
			funcArr.push(func);
		};

		// 接收信息 类似于bus.$on
		emitter.on("form-item-created", callback); // 此处的callback是子组件的validDateInput函数
		onUnmounted(() => {
			emitter.off("form-item-created", callback);
			funcArr = [];
		});

		return {
			submitForm,
		};
	},
});
</script>

<style>
</style>